package com.supor.aiot.home.ui.device;

import android.annotation.SuppressLint;
import android.app.Application;
import android.text.TextUtils;

import com.android.baseconfig.common.utils.GsonUtil;
import com.android.baseconfig.common.utils.Logc;
import com.google.gson.reflect.TypeToken;
import com.supor.aiot.common.app.api.DeviceImpl;
import com.supor.aiot.common.base.BaseViewModel;
import com.supor.aiot.common.entity.ProductType;
import com.supor.aiot.common.entity.Result;
import com.supor.aiot.common.helper.GlobalDataCache;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import androidx.annotation.NonNull;
import androidx.lifecycle.MutableLiveData;

public class AddDeviceViewModel extends BaseViewModel {

    // content数据
    private final MutableLiveData<List<ProductType.ProductModel>> data = new MutableLiveData<>();
    // title数据
    private final MutableLiveData<List<ProductType>> dataTitle = new MutableLiveData<>();
    // content 的 title position  外面的i对应的 titlePositions.get(i)
    private final MutableLiveData<List<Integer>> titlePositions = new MutableLiveData<>();
    // 用来滑动定位 第一个Integer为内容的position，第二个Integer为对应的分类position
    private HashMap<Integer, Integer> hashMap;
    // 辅助滑动定位 第一个Integer为分类position，第二个Integer为对应的内容标题的position
    private HashMap<Integer, Integer> positionTitleMap;

    public MutableLiveData<List<ProductType.ProductModel>> getData() {
        return data;
    }

    public MutableLiveData<List<ProductType>> getDataTitle() {
        return dataTitle;
    }

    public MutableLiveData<List<Integer>> getTitlePositions() {
        return titlePositions;
    }

    public HashMap<Integer, Integer> getHashMap() {
        return hashMap;
    }

    public HashMap<Integer, Integer> getPositionTitleMap() {
        return positionTitleMap;
    }

    public AddDeviceViewModel(@NonNull Application application) {
        super(application);
        hashMap = new HashMap<>();
        positionTitleMap = new HashMap<>();
    }


    private final MutableLiveData<Result> bindResult = new MutableLiveData<>();

    public MutableLiveData<Result> getBindResult() {
        return bindResult;
    }

    public void bindNFCDevice(String mac, String modelId) {
        Map<String, String> map = new HashMap<>();
        map.put("productModel", modelId);
        map.put("mac", mac);
        map.put("bindType", "nfc");
        map.put("thirdType", "Supor");
        DeviceImpl.getInstance().bind(map).subscribe(result -> {
            if (result.isSuccess() && result.data != null) {
                bindResult.setValue(new Result.Success(result.data));
            } else {
                bindResult.setValue(new Result.Error("bindNFCDevice failed"));
            }
        }, throwable -> {
            Logc.e("bindNFCDevice: " + throwable);
            bindResult.setValue(new Result.Error(new Exception(throwable)));
        });
    }

    @SuppressLint("CheckResult")
    public void getAllProduct() {
        if (GlobalDataCache.productTypeList != null) {
            getNavigationJson();
            return;
        }
        DeviceImpl.getInstance().getAllProduct().subscribe(result -> {
            List<ProductType> productTypeList = result.data.rows;
            List<ProductType> tempList = new ArrayList<>();
            for (ProductType productType : productTypeList) {
                if (productType.Children == null) {
                    continue;
                }
                for (ProductType.ProductModel child : productType.Children) {
                    if (TextUtils.isEmpty(child.modelPicture)) {
                        child.modelPicture = productType.modelPicture;
                    }
                    // pid
                    child.productId = child.salsModelName;
//                    if ("Q8".equalsIgnoreCase(child.modelId)) {
//                        child.productId = "C003"; // Q8破壁机
//                    }
                }
                tempList.add(productType);
            }
            GlobalDataCache.productTypeList =
                    GsonUtil.getInstance().toObject(GsonUtil.getInstance().toJson(tempList), new TypeToken<List<ProductType>>() {
            }.getType());
            getNavigationJson();
        }, throwable -> {
            Logc.e("accept: " + throwable);
            data.setValue(new ArrayList<>());
            // ToastUtils.getInstance().showCustomToast("获取产品失败");
        });
    }

    public void getNavigationJson() {
        List<ProductType> productTypeList = GlobalDataCache.productTypeList;
        List<ProductType.ProductModel> productModels = new ArrayList<>();
        for (ProductType productType : productTypeList) {
            if (TextUtils.isEmpty(productType.modelTypeName)) {
                productType.modelTypeName = productType.Children.get(0).modelTypeName;
            }
            productType.selected = false;
            productModels.addAll(productType.Children);
        }
        TreeMap<String, List<ProductType.ProductModel>> map = new TreeMap<>();
        for (ProductType.ProductModel productModel : productModels) {
            if (map.containsKey(productModel.modelTypeId)) {
                map.get(productModel.modelTypeId).add(productModel);
            } else {
                List<ProductType.ProductModel> typeList = new ArrayList<>();
                typeList.add(productModel);
                map.put(productModel.modelTypeId, typeList);
            }
        }

        // title
        dataTitle.setValue(productTypeList);
        // content
        ArrayList<ProductType.ProductModel> list = new ArrayList<>();
        // content部分对应分类的position
        ArrayList<Integer> positions = new ArrayList<>();
        positions.add(list.size());
        for (int i = 0; i < productTypeList.size(); i++) {
            ProductType dataBean = productTypeList.get(i);
            ProductType.ProductModel bean = new ProductType.ProductModel();
            if (!TextUtils.isEmpty(dataBean.modelTypeName)) {
                bean.modelTypeName = dataBean.modelTypeName;
            } else {
                bean.modelTypeName = dataBean.Children.get(0).modelTypeName;
            }
            // positions.add(list.size());
            // if (i != 0) {
            //     // 最后一个item可能有一个或两个
            //     hashMap.put(list.size() - 1, i - 1);
            //     hashMap.put(list.size() - 2, i - 1);
            // }
            hashMap.put(list.size(), i);
            positionTitleMap.put(i, list.size());
            list.add(bean);
            list.addAll(dataBean.Children);
            positions.add(list.size());
        }
        ProductType.ProductModel blank = new ProductType.ProductModel();
        blank.productId = "blank";
        list.add(blank);
        titlePositions.setValue(positions);
        // Logc.e("getNavigationJson: list: " + list);
        data.setValue(list);

    }
}
